package com.demo.study.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class T02_ThreadPoolExecutor {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 10; i++) {
            // executorService.execute(new Counter(i)); // 无返回值
            Future<String> future = executorService.submit(new FutureCounter()); // 有返回值
            System.out.println(future.get());
        }

        // executorService.shutdown();
    }

    static class Counter implements Runnable {
        private final int id;

        public Counter(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println(id + ": " + threadName);
        }
    }

    static class FutureCounter implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("开始执行");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("执行完成");
            return null;
        }
    }
}
